/*
 * Copyright the original author or authors.
 *
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.mozilla.org/MPL/MPL-1.1.html *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Authors:
 *   Russell Weir damonsbane/gmail dot com
 */
package hxbase.flash.net;
import hxbase.events.Event;

/**
	onSync delivers all events, including code : clear
	Change is when an update is received: name, oldValue
	Reject sends name, oldValue
	Sucess sends only the name of the variable set.
*/
class SharedObjectEvents extends EventGroup {
	var onSync	: Event<Array<Dynamic>->Void>;
	var onSyncChange : Event<String->Dynamic->Void>;
	var onSyncReject : Event<String->Dynamic->Void>;
	var onSyncSuccess : Event<String->Void>;

	override private function init() {
		onSync = new Event<Array<Dynamic>->Void>(this);
		onSyncChange = new Event<String->Dynamic->Void>(this);
		onSyncReject = new Event<String->Dynamic->Void>(this);
		onSyncSuccess = new Event<String->Void>(this);
	}
}

class SharedObject
	extends hxbase.flash.events.EventDispatcher<SharedObjectEvents>,
#if flash9
	implements hxbase.flash.IFlashWrapper<flash.net.SharedObject>
#else flash
	implements hxbase.flash.IFlashWrapper<flash.SharedObject>
#end
{
	public static var defaultObjectEncoding(getDefaultObjectEncoding, setDefaultObjectEncoding) : Int;
	public var name(default,null) : String;
	public var persistent(default,null) : Bool;
	public var connected(default, null) : Bool;
	public var path(default, null) : String;
	public var secure(default, null) : Bool;
#if flash9
	var so : flash.net.SharedObject;
#else flash
	var so : flash.SharedObject;
#end

	public function new(name, ?pathOrUri, ?secure) {
		super();
		events = new SharedObjectEvents();
		this.name = name;
		this.path = pathOrUri;
		this.secure = secure;
		this.persistent = true;
	}

	public function get(key : String) {
		return Reflect.field(so.data, key);
	}

	public function set(key : String, value : Dynamic) : Bool {
		so.setProperty(key, value);
		return true;
	}

	public static function setDefaultObjectEncoding(v : Int) : Int {
		if(v != 0) v = 0;
#if flash9
		flash.net.SharedObject.defaultObjectEncoding = 0;
#end
		return v;
	}

	public static function getDefaultObjectEncoding() : Int {
#if flash9
		return flash.net.SharedObject.defaultObjectEncoding;
#end
		return 0;
	}

	public function getObject() {
		return so;
	}

	function __init__() {
		flash.net.SharedObject.defaultObjectEncoding = 0;
	}
}

